package com.imooc.mq;

import com.google.gson.Gson;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 短信监听消费者
 * @author liansen
 * @create 02-19-22:59
 */
@Slf4j
@Component
public class RabbitMQSMSConsumer {

//    @RabbitListener(queues = {RabbitMQSMSConfig.SMS_QUEUE})
//    public void watchQueue(String content, Message msg){
//        //获取路由键
//        String receivedRoutingKey = msg.getMessageProperties().getReceivedRoutingKey();
//        log.info("routing-key:" + receivedRoutingKey);
//        //获取接收到的内容
//        log.info("content:" + content);
//
//        if(receivedRoutingKey.equalsIgnoreCase(RabbitMQSMSConfig.ROUTING_KEY_SMS_SEND_LOGIN)){
//            SMSContentQO contentQO = new Gson().fromJson(content, SMSContentQO.class);
//            //向手机发送短信验证码
//            log.info("通过mq向手机发送短信验证码:" + contentQO.getContent());
//        }
//    }

    @RabbitListener(queues = {RabbitMQSMSConfig.SMS_QUEUE})
    public void watchQueue(String content, Message msg, Channel channel) throws IOException {

        try {
            //获取路由键

            String receivedRoutingKey = msg.getMessageProperties().getReceivedRoutingKey();
            log.info("routing-key:" + receivedRoutingKey);
            SMSContentQO contentQO = new Gson().fromJson(content, SMSContentQO.class);
            log.info("通过mq向手机发送短信验证码:" + contentQO.getContent());
            /**
             * long deliveryTag: 消息投递的标签,
             * boolean multiple: 批量确认所有消费者获得的消息
             */
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), true);
            log.info("deliveryTag:" + msg.getMessageProperties().getDeliveryTag()); // 1
        }catch (Exception e){
            e.printStackTrace();
            /**
             * long deliveryTag: 消息投递的标签,
             * boolean multiple: 批量确认所有消费者获得的消息
             * requeue: 是否重回队列
             */
            channel.basicNack(msg.getMessageProperties().getDeliveryTag(), true, true);
        }
    }
}
